package com.songcha.sakura.ui.view.video

import android.content.Context
import android.graphics.SurfaceTexture
import android.media.AudioManager
import android.media.MediaPlayer
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.AttributeSet
import android.view.Gravity
import android.view.Surface
import android.view.TextureView
import android.view.ViewGroup
import android.widget.FrameLayout
import com.songcha.library_common.util.LogUtil
import com.songcha.library_common.util.ScreenUtil
import com.songcha.library_common.util.ToastUtil
import java.lang.ref.WeakReference


class CustomVideoPlayer : FrameLayout ,
        TextureView.SurfaceTextureListener,
        MediaPlayer.OnPreparedListener,MediaPlayer.OnErrorListener,
        MediaPlayer.OnInfoListener,
        MediaPlayer.OnCompletionListener,
        MediaPlayer.OnVideoSizeChangedListener {
    private lateinit var mContainer:FrameLayout
    private lateinit var mTextureView: VideoTextureView
    private lateinit var mController: VideoController
    private var mSurfaceTexture:SurfaceTexture?=null
    private lateinit var mMediaPlayer:MediaPlayer
    private var mUrl:String=""
    private var mTitle:String=""
    private var mSurface:Surface?=null
    //private var mContext:Context?=null

    private val MODE_NORMAL=1
    private val MODE_FULL_SCREEN=2

    private val STATE_IDLE=3
    private val STATE_PREPARING=4
    private val STATE_PREPARED=5
    private val STATE_START=6
    private val STATE_PAUSED=7
    private val STATE_STOP=8
    private val STATE_COMPLETED=9

    private val mCurrentMode=MODE_NORMAL

    private val mCurrentState=STATE_IDLE

    private var mProgressListenThread:Thread?=null

    private var MSG_PROGREDD_CHANGE=1


    constructor(context: Context) : super(context) {
        initView(context,null)
    }

    constructor(context: Context, attrs: AttributeSet):this(context,attrs,0){

    }

    constructor(context: Context, attrs: AttributeSet, defStyle:Int):this(context,attrs,defStyle,0){

    }

    constructor(context: Context, attrs: AttributeSet, defStyle:Int, defRes:Int):super(context,attrs,defStyle,defRes){
        initView(context,attrs)
    }

    private fun initView(context: Context, attrs: AttributeSet?){
       // mContext=context

        mMediaPlayer=MediaPlayer()
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)

        mTextureView=VideoTextureView(context)
        mTextureView.surfaceTextureListener=this

        mController=VideoController(context)
        mController.setVideoPlayer(this)

        mContainer=FrameLayout(context)
        val containerParams=LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT)
        mContainer.layoutParams=containerParams


        //默认16：9
        val textureParams=LayoutParams(ScreenUtil.getScreenHeight(context)*16/9,ViewGroup.LayoutParams.MATCH_PARENT)
        textureParams.gravity=Gravity.CENTER
        mTextureView.layoutParams=textureParams
        mContainer.addView(mTextureView)


        mContainer.addView(mController,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT)

        addView(mContainer)

       // openMediaPlayer()
    }


    fun getCurrentModel():Int{
        return mCurrentMode
    }

    fun getCurrentState():Int{
        return mCurrentState
    }

    fun getTextureView():VideoTextureView{
        return mTextureView
    }

    fun getController():VideoController{
        return mController
    }

    fun getMediaPlayer():MediaPlayer{
        return mMediaPlayer
    }

    fun setTitle(title:String){
        mTitle=title
    }

    fun getName():String{
        return mTitle
    }

    fun setUrl(url:String){
        mUrl=url
    }

    /*fun pause(){
        mController.onPause()
        mController.savePlayHistoryProgress()
    }*/

   /* fun savePlayProgress(){
        mController.savePlayHistoryProgress()
    }*/



     private fun openMediaPlayer(){
        //mMediaPlayer.prepareAsync()

        mContainer.keepScreenOn=true
        mMediaPlayer.setOnPreparedListener(this)
        mMediaPlayer.setOnVideoSizeChangedListener(this)
        mMediaPlayer.setOnCompletionListener (this)
        mMediaPlayer.setOnErrorListener(this)
        mMediaPlayer.setOnInfoListener(this)
        //mMediaPlayer.setOnBufferingUpdateListener(this)

        try{
            mMediaPlayer.setDataSource(context, Uri.parse(mUrl))
            if(mSurfaceTexture!=null){
                if(mSurface==null)
                    mSurface=Surface(mSurfaceTexture)
                mMediaPlayer.setSurface(mSurface)
                mMediaPlayer.prepareAsync()
            }

        }catch (e:Exception){
            ToastUtil.show("播放错误")
            e.printStackTrace()
        }
    }


    override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
        //LogUtil.log("onSurfaceTextureAvailable")
        if(mSurfaceTexture==null){
            mSurfaceTexture=surface
            openMediaPlayer()
        }else{
            mTextureView.setSurfaceTexture(mSurfaceTexture!!)
        }

    }

    override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {

    }

    override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
        return true
    }

    override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {

    }


    val mProgressHandler=object: Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when(msg.what){
                MSG_PROGREDD_CHANGE->mController.setProgress(msg.arg1)
            }
        }
    }

    //静态内部类加弱引用防止内存泄漏
    companion object{
        private var wrCvp:WeakReference<CustomVideoPlayer>?=null
        class ProgressRunnable(cvp:CustomVideoPlayer,val mp: MediaPlayer):Runnable{

            init {
                wrCvp=WeakReference(cvp)
            }

            override fun run() {
                if(wrCvp==null) return
                val cvp=wrCvp!!.get() ?: return

                try {
                    while (true) {
                        if(mp.isPlaying){
                            val p=mp.currentPosition*1.0/mp.duration*100
                            val msg=Message()
                            msg.what=cvp.MSG_PROGREDD_CHANGE
                            msg.arg1=p.toInt()
                            cvp.mProgressHandler.sendMessage(msg)
                        }
                        Thread.sleep(1000)
                    }
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }

            }

        }
    }

    override fun onPrepared(mp: MediaPlayer?) {
        //ToastUtil.show("onPrepared")
        if(mp==null) return
        //if(isActivated)
        mController.onPrepared()
        mp.start()

        if(mProgressListenThread==null && mp.duration>0){
            mProgressListenThread=Thread(ProgressRunnable(this,mp))
            mProgressListenThread?.start()
        }

        mController.readPlayHistoryProgress()

    }

    override fun onError(mp: MediaPlayer?, what: Int, extra: Int): Boolean {
        LogUtil.log("mediaplayer error",what,extra)
        //ToastUtil.show("视频播放错误")
        return true
    }

    override fun onInfo(mp: MediaPlayer?, what: Int, extra: Int): Boolean {
        if(mp==null) return true

        return true
    }

    override fun onCompletion(mp: MediaPlayer?) {
        mController.onCompletion()
    }

    override fun onVideoSizeChanged(mp: MediaPlayer?, width: Int, height: Int) {
        //ToastUtil.show("onVideoSizeChanged")
        LogUtil.log("onVideoSizeChanged",width,height)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        //防止内存泄漏
        mProgressHandler.removeCallbacksAndMessages(null)
        mProgressListenThread?.interrupt()
    }


}